<template>
  <Modal
    v-model="showCreateEnvironmentModal"
    title="创建环境"
    width="950"
    :mask-closable="false"
    @on-cancel="handleCreateEnvironmentCancel"
  >
    <Tabs name="environment-add-tabs" :animated="true">
      <TabPane label="基础信息" tab="environment-add-tabs">
        <Form
          label-position="right"
          :label-width="80"
          ref="environmentForm"
          :model="environmentForm"
          :rules="environmentValidate"
        >
          <FormItem label="环境名称" prop="name">
            <Input clearable v-model="environmentForm.name" />
          </FormItem>
          <FormItem label="环境地址" prop="base_url">
            <Input
              clearable
              v-model="environmentForm.base_url"
              placeholder="格式：域名(或IP):端口号，示例：https://www.baidu.com"
            />
          </FormItem>
          <FormItem label="备注">
            <Input
              clearable
              type="textarea"
              :rows="10"
              v-model="environmentForm.remark"
            />
          </FormItem>
        </Form>
      </TabPane>
      <TabPane label="全局参数配置" tab="environment-add-tabs">
        <JsonEditor
          v-model="environmentForm.global_variables"
          jsonEditorId="createEnvironmentGlobalVariables"
          style="height: 500px"
        ></JsonEditor>
      </TabPane>
    </Tabs>
    <div slot="footer">
      <Button type="default" @click="handleCreateEnvironmentCancel"
        >取消</Button
      >
      <Button
        type="primary"
        @click="handleCeateEnvironmentSubmit('environmentForm')"
        >确定</Button
      >
    </div>
  </Modal>
</template>

<script>
import JsonEditor from "_c/json-editor";
import { createEnv } from "@/api/HttpAutoTestService/environment";

export default {
  name: "environment-create",
  components: {
    JsonEditor,
  },
  props: {
    createEnvironment: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    showCreateEnvironmentModal: {
      get() {
        return this.createEnvironment;
      },
      set(val) {
        this.$emit("update:createEnvironment", val);
      },
    },
  },
  data() {
    const validateBaseUrl = (rule, value, callback) => {
      const base_url_reg = /^(https?:\/\/)(.*)/;
      const url = value.toLowerCase();
      if (!base_url_reg.test(url)) {
        callback(new Error("必须以 http:// 或 https:// 开头，不区分大小写"));
      }
      callback();
    };
    return {
      environmentForm: {
        name: "",
        base_url: "",
        remark: "",
        global_variables: {},
      },
      environmentValidate: {
        name: [{ required: true, message: "请输入环境名称", trigger: "blur" }],
        base_url: [
          { required: true, message: "请输入环境地址", trigger: "blur" },
          { validator: validateBaseUrl, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    handleCeateEnvironmentSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.environmentForm.global_variables === "") {
            this.environmentForm.global_variables = {};
          }

          createEnv(this.environmentForm)
            .then((res) => {
              if (res.status === 201) {
                this.$Message.info("创建成功");
                this.handleCreateEnvironmentCancel();
              } else {
                this.$Message.error("创建失败");
              }
            })
            .catch((err) => {
              this.$Modal.error({
                title: "系统异常，请联系管理员……",
                content: JSON.stringify(err),
                closable: true,
              });
            });
        }
      });
    },
    handleCreateEnvironmentCancel() {
      this.showCreateEnvironmentModal = false;
      this.environmentForm = {
        name: "",
        base_url: "",
        remark: "",
        global_variables: {},
      };
      this.$emit("initEnvTable");
      this.$refs['environmentForm'].resetFields();
    },
  },
};
</script>

<style scoped>
</style>
